package com.example.mywood;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import myapp.MyApp;
import util.DensityUtil;
import util.SystemStatusManager;
import util.UploadUtil;

public class EditInfoActivity2 extends BaseActivity {


    private LinearLayout ll_reback;
    private LinearLayout ll_phone;
    private LinearLayout ll_nickname;
    private LinearLayout ll_email;
    private Intent intent = null;
    private Context context;
    private ImageView img_userlogo;
    private Uri photoUri;
    private Uri photoUricat;
    private String UppicPath;
    private boolean is_shot;//是否来源于拍照
    private MyApp myapp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_editinfo);
        setTranslucentStatus();
        context = this;
        myapp = (MyApp) getApplicationContext();
        initView();
        initLin();


    }


    private void initView() {
        ll_reback = findViewById(R.id.ll_reback);
        ll_phone = findViewById(R.id.ll_phone);
        ll_nickname = findViewById(R.id.ll_nickname);
        ll_email = findViewById(R.id.ll_email);
        img_userlogo = findViewById(R.id.img_userlogo);
    }


    private void initLin() {
        ll_reback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        ll_phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intent = new Intent(context,RevisePhoneActivity.class);
                startActivity(intent);
            }
        });
        ll_nickname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intent = new Intent(context,ChangeNameActivity.class);
                startActivity(intent);
            }
        });
        img_userlogo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ActivityCompat.checkSelfPermission(EditInfoActivity2.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED ||
                            ActivityCompat.checkSelfPermission(EditInfoActivity2.this,Manifest.permission.READ_EXTERNAL_STORAGE)
                                    != PackageManager.PERMISSION_GRANTED ) {
                        // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
                        ActivityCompat.requestPermissions(EditInfoActivity2.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 10);
                    } else {
                        doUpFile();
                    }
                }else{
                    doUpFile();
                }

            }
        });
    }
    /**
     * 设置状态栏背景状态
     */
    public  void setTranslucentStatus()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            Window win =  getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);
        }
        SystemStatusManager tintManager = new SystemStatusManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(0);//状态栏无背景
    }


    /**
     * 授权回调函数
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case 10:
                if (grantResults.length > 0) {
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        // 获取到权限，作相应处理
                        doUpFile();
                    } else {
                        // 没有获取到权限，做特殊处理
                        showPermissionDialog();
                    }
                } else {
                    showPermissionDialog();
                }
                break;
            default:
                break;
        }
    }

    // 启动应用的设置
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }
    /**
     * 提示打开设置对话框
     */
    private void showPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(EditInfoActivity2.this);
        builder.setTitle(getString(R.string.help));
        builder.setMessage(getString(R.string.open_proess));
        // 拒绝, 退出应用
        builder.setNegativeButton(getString(R.string.exit), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });

        builder.setPositiveButton(getString(R.string.text_btn_set), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startAppSettings();
            }
        });
        builder.setCancelable(false);
        builder.show();
    }


    private  void doUpFile(){


        final CharSequence[] items = {getString(R.string.album), getString(R.string.take_picture), getString(R.string.cancel)};
        AlertDialog dlg = new AlertDialog.Builder(new ContextThemeWrapper(context, R.style.AlertDialogCustom)).setTitle(getString(R.string.select_picture)).setItems(items,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        //这里item是根据选择的方式，        在items数组里面定义了两种方式，拍照的下标为1所以就调用拍照方法
                        if (item == 1) {
                                            /* Intent getImageByCamera= new Intent("android.media.action.IMAGE_CAPTURE");
                                                     startActivityForResult(getImageByCamera, 1);   */
                            if(Build.VERSION.SDK_INT >=24) {
                                try{
                                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                                    File path = null;
                                    if (hasSdcard()) {
                                        path = Environment.getExternalStoragePublicDirectory(
                                                Environment.DIRECTORY_DCIM);

                                    }
                                    Date date = new Date();
                                    String timeStamp = getTime(date, "yyyyMMdd_HHmmss", Locale.CHINA);
                                    String imageFileName = "Camera/" + "IMGb_" + timeStamp + ".jpg";
                                    File image = new File(path, imageFileName);
                                    photoUri = FileProvider.getUriForFile(EditInfoActivity2.this, "com.example.m6wmr.fileprovider", image);
                                    List resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
                                    if (resInfoList.size() == 0) {

                                        Toast.makeText(context,getString(R.string.no_repeat_app),Toast.LENGTH_SHORT);
                                        return;
                                    }
                                    Iterator resInfoIterator = resInfoList.iterator();
                                    while (resInfoIterator.hasNext()) {
                                        ResolveInfo resolveInfo = (ResolveInfo) resInfoIterator.next();
                                        String packageName = resolveInfo.activityInfo.packageName;
                                        grantUriPermission(packageName, photoUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                                    }

                                    ContentValues values = new ContentValues();
                                    values.put(MediaStore.Audio.Media.TITLE, imageFileName);
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                                            | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                                    startActivityForResult(intent, 1);
                                }catch (Exception e){
                                    dialog.dismiss();
                                }
                            }else {
                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                                        "yyyy_MM_dd_HH_mm_ss");
                                String filename = timeStampFormat.format(new Date());
                                ContentValues values = new ContentValues();
                                values.put(MediaStore.Audio.Media.TITLE, filename);
                                photoUri = getContentResolver().insert(
                                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                                startActivityForResult(intent, 1);
                            }



                        } else if (item == 0) {
                            Intent getImage;
                            if (Build.VERSION.SDK_INT < 19) {
                                getImage = new Intent(Intent.ACTION_GET_CONTENT);
                                getImage.setType("image/*");
                                startActivityForResult(getImage, 0);
                            }else if(Build.VERSION.SDK_INT >=24){
                                // photo_image = createPublicImageFile();
                                try{
                                    File file =  createPublicImageFile();
                                    Uri uri = FileProvider.getUriForFile(EditInfoActivity2.this, "com.example.mywood.fileprovider", file);
                                    getImage = new Intent(Intent.ACTION_PICK, uri);
                                    startActivityForResult(getImage, 0);
                                }catch (Exception e){
                                    dialog.dismiss();
                                }



                            }else{
                                getImage = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                startActivityForResult(getImage, 0);
                            }


                        } else {
                            dialog.dismiss();
                        }
                    }

                }).create();
        dlg.show();

    }

    public static boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
    private String getTime(Date date, String mode, Locale locale) {
        SimpleDateFormat format = new SimpleDateFormat(mode, locale);
        return format.format(date);
    }

    private File createPublicImageFile() throws IOException {
        File path = null;
        if (hasSdcard()) {
            path = Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DCIM);
        }
        Date date = new Date();
        String timeStamp = getTime(date, "yyyyMMdd_HHmmss", Locale.CHINA);
        String imageFileName = "Camera/" + "IMG_" + timeStamp + ".jpg";
        File image = new File(path, imageFileName);
        //  mPublicPhotoPath = image.getAbsolutePath();
        return image;
    }

private File imgFile = null;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        ContentResolver resolver = getContentResolver();
        Log.e(">>>>>>>>>>>>>>", "拍照返回" + requestCode);

        /*if (requestCode == MyApp.Login_REQUEST_Code) {
            if (resultCode == MyApp.Result_SUCC_Code) {
				*//*ll_nologin.removeAllViews();
				onCreate(savedInstanceState);*//*
                Intent intent = new Intent(MyuserActivity.this, UserCenterActivity2.class);
                startActivity(intent);
            }

        }
*/
        switch (requestCode) {
            // 如果是直接从相册获取
            case 0:
                Log.e("com.bangk.yh", "fanhuicuowu"+data.toString() + requestCode);
                if (data != null && data.getData() != null) {
                    startPhotoZoom(data.getData());
                    Log.e("com.bangk.yh", "3333333333"+data.getData() + "    " + requestCode);
                }
                break;
            // 如果是调用相机拍照时
            case 1:
//                Log.e("com.bangk.yh", "如果是调用相机拍照时1111"+data.toString() + requestCode);
                if (null != data && data.getData() != null) {
                    startPhotoZoom(data.getData());
                } else {
                    if (photoUri != null) {
                        startPhotoZoom(photoUri);
                    }
                }

                break;

            case 3:
                /**
                 * 非空判断大家一定要验证，如果不验证的话，
                 * 在剪裁之后如果发现不满意，要重新裁剪，丢弃
                 * 当前功能时，会报NullException，小马只
                 * 在这个地方加下，大家可以根据不同情况在合适的
                 * 地方做判断处理类似情况
                 *
                 */





                if (photoUricat != null) {

                    Log.e("----------------", "xxxxxxxxxxx");
//                    Util.dismisDialog();
                    System.out.println("上传裁剪图片");

                    // Bundle extras = data.getExtras();
                    Bitmap myBitmap =null;
                    try {
                        myBitmap =getThumbnail(photoUricat, DensityUtil.dp(context, 150), DensityUtil.dp(context, 150));
                    } catch (Exception e) {
                        myBitmap =null;
                        Log.e("com.bangk.yh","tttttttttttttttttttttttttt"+ e.getMessage().toString());
                        e.printStackTrace();
                    }
                    if(myBitmap == null){
                        Log.e("com.bangk.yh","tingzhi"+ photoUricat.toString());
                        break;
                    }
                    // Bitmap	myBitmap = getSmallBitmap(picPath);

                     /*
                    Bundle extras = data.getExtras();
                    Bitmap myBitmap = (Bitmap) extras.get("data"); */
                    FileOutputStream fileOutputStream = null;

                    try {
                        // 获取 SD 卡根目录
                        String saveDir = Environment.getExternalStorageDirectory() + "/meitian_photos";
                        // 新建目录
                        File dir = new File(saveDir);
                        if (!dir.exists()) dir.mkdir();
                        // 生成文件名
                        SimpleDateFormat t = new SimpleDateFormat("yyyyMMddssSSS");
                        String filename = "MT" + (t.format(new Date())) + ".jpg";
                        // 新建文件
                        File file = new File(saveDir, filename);
                        imgFile = file;
                        // 打开文件输出流
                        fileOutputStream = new FileOutputStream(file);
                        // 生成图片文件
                        myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                        // 相片的完整路径
                        UppicPath = file.getPath();
                        is_shot = true;

                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (fileOutputStream != null) {
                            try {
                                fileOutputStream.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    System.out.println("选择相片路径:" + UppicPath);
                    if (UppicPath == null) {

                    } else {
//                        Util.showDialog(context, getString(R.string.upload_img), getString(R.string.please_wait));
//                        uploadFile();
                        String httpUrl =myapp.getWebConfig() + "/admin/ajax/upload";
                        String sssss = UploadUtil.uploadFile(imgFile,httpUrl);
                        System.out.println("选择相片路径:" + sssss);
                    }


                }
                break;

            case 4:

                Log.e("fjdosflkjsdfjsdolf", "changename");


                break;
            default:

                break;


        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void startPhotoZoom(Uri uri) {
        /*
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
         * yourself_sdk_path/docs/reference/android/content/Intent.html
         * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能,
         * 是直接调本地库的，小马不懂C C++  这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么
         * 制做的了...吼吼
         */
        photoUricat = null;
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Log.e("com.bangk.yh",uri.toString()+"xxxxxxxxxx");

            // Log.e("com.bangk.yh",url+"xxxxxxbbbbbbxxxx");
            if (Build.VERSION.SDK_INT >= 24){
                //    String url = getPath(context, uri);
                //  Log.e("com.bangk.yh", file);
                //     File file = new File(url);
                //  Uri uri2 = FileProvider.getUriForFile(MyuserActivity.this, "com.example.m6wmr.fileprovider", uri);


                //  mFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test/jd_id_origin_pictrue.jpg");
                //  mUri = FileProvider.getUriForFile(this, "com.zera.hello", mFile);
                /*
                try{

                    File file =  createPublicImageFile();
                    photoUricat = FileProvider.getUriForFile(MyuserActivity.this, "com.example.m6wmr.fileprovider", file);
                    intent.setDataAndType(uri, "image/*");
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                            | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    intent.putExtra("return-data", false);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUricat);
                    intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

                    //photoUricat
                }catch (Exception e){
                    return;
                } */
                //    String url = getPath(context, uri);
                try {
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    intent.setDataAndType(uri, "image/*");
                    File file = createPublicImageFile();
                    //  photoUricat = FileProvider.getUriForFile(MyuserActivity.this, "com.example.m6wmr.fileprovider", file);


                    Log.e("com.bangk.yh",uri.toString()+"xxxxxx24");


                    photoUricat = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUricat);
                    intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
                }catch (Exception e){
                    return;
                }


            }else{
                String url = getPath(context, uri);
                intent.setDataAndType(Uri.fromFile(new File(url)), "image/*");
                photoUricat = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUricat);
                intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

            }
        } else {
            intent.setDataAndType(uri, "image/*");
            photoUricat = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUricat);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        }


        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);

        intent.putExtra("outputFormat", "JPEG");// 图片格式
        intent.putExtra("noFaceDetection", true);// 取消人脸识别



        //   photoUri = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");
        //intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        // intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        //intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());//
        startActivityForResult(intent, 3);
    }
    public Bitmap getThumbnail(Uri uri,int reqWidth,int reqHeight)throws IOException {
        InputStream input = getContentResolver().openInputStream(uri);

        BitmapFactory.Options options =new BitmapFactory.Options();
        options.inJustDecodeBounds=true;
        BitmapFactory.decodeStream(input, null,options);
        if((options.outWidth== -1) || (options.outHeight== -1))
            return null;
        options.inSampleSize=calculateInSampleSize(options,reqWidth,reqHeight);
        options.inJustDecodeBounds=false;
        input.close();
        input = getContentResolver().openInputStream(uri);
        Bitmap bitmap = BitmapFactory.decodeStream(input, null,options);
        input.close();
        return bitmap;
    }
    private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math. round((float)height / ( float)reqHeight);
            } else {
                inSampleSize = Math. round((float)width / ( float)reqWidth);
            }
        }
        return inSampleSize;
    }
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    // 上传图片
    private boolean uploadFile() {
        new Thread() {
            public void run() {
                super.run();

                Message msg = new Message();
                String end = "\r\n";
                String twoHyphens = "--";
                String boundary = "*****";
                try {
                    String httpUrl =myapp.getWebConfig() + "/admin/ajax/upload";
                    Log.e("xxx", httpUrl);
                    System.out.println("文件名-" + getFileName(UppicPath));
                    System.out.println("提交连接-" + httpUrl);
                    URL url = new URL(httpUrl);


                    HttpURLConnection con = (HttpURLConnection) url
                            .openConnection();
                    /* 允许Input、Output，不使用Cache */
                    con.setDoInput(true);
                    con.setDoOutput(true);
                    con.setUseCaches(false);
                    /* 设置传送的method=POST */
                    con.setRequestMethod("POST");
                    /* setRequestProperty */
                    con.setRequestProperty("Connection", "Keep-Alive");
                    con.setRequestProperty("Charset", "UTF-8");
                    con.setRequestProperty("Content-Type",
                            "multipart/form-data;boundary=" + boundary);

                    /* 设置DataOutputStream */
                    DataOutputStream ds = new DataOutputStream(
                            con.getOutputStream());
                    ds.writeBytes(twoHyphens + boundary + end);
                    ds.writeBytes("Content-Disposition: form-data; "
                            + "name=\"imgFile\";filename=\""
                            + UppicPath + "\"" + end);
//                            + getFileName(UppicPath) + ".jpg" + "\"" + end);
                    ds.writeBytes(end);
                    /* 取得文件的FileInputStream */
                    FileInputStream fStream = new FileInputStream(UppicPath);
                    /* 设置每次写入1024bytes */
                    int bufferSize = 1024;
                    byte[] buffer = new byte[bufferSize];
                    int length = -1;
                    /* 从文件读取数据至缓冲区 */
                    while ((length = fStream.read(buffer)) != -1) {
                        /* 将资料写入DataOutputStream中 */
                        ds.write(buffer, 0, length);
                    }
                    ds.writeBytes(end);
                    ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
                    /* close streams */
                    fStream.close();
                    ds.flush();
                    /* 取得Response内容 */
                    InputStream is = con.getInputStream();
                    int ch;
                    StringBuffer b = new StringBuffer();
                    while ((ch = is.read()) != -1) {
                        b.append((char) ch);
                    }
                    /* 将Response显示于Dialog */
                    // showDialog("上传成功"+b.toString().trim());

                    System.out.println("返回数据-" + b.toString().trim());
                    String backstrl = b.toString().trim();

                    /* 关闭DataOutputStream */
                    ds.close();
//                    Util.dismisDialog();
                    if (is_shot == true) {
                        //调用删除图片
                        File file = new File(UppicPath);
                        file.delete();
//							System.out.println("删除图片");
                    }


                    try {

                        JSONObject json = new JSONObject(backstrl);
                        Log.d("xxx", backstrl);

                        if (json.getString("code").equals("0")) {
                            msg.obj = json.getString("msg");
                            msg.arg1 = 0;
                            handler.sendMessage(msg);
                            return;
                        }
                        /*if (json.isNull("msg")) {

                            msg.arg1 = 1;
                            handler.sendMessage(msg);
                            return;
                        }*/

                        JSONObject backdata = json.getJSONObject("data");

                        msg.obj = backdata.getString("url");
                        msg.arg1 = 3;
                        handler.sendMessage(msg);
                        return;
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block

                        e.printStackTrace();

                        msg.arg1 = 1;
                        handler.sendMessage(msg);
                        return;
                    }

                } catch (Exception e) {
//                    Util.dismisDialog();

                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                    return;
                }

            }

            public synchronized void start() {
                super.start();
            }
        }.start();
        return false;
    }

    public String getFileName(String pathandname) {

        int start = pathandname.lastIndexOf("/");
        int end = pathandname.lastIndexOf(".");
        if (start != -1 && end != -1) {
            return pathandname.substring(start + 1, end);
        } else {
            return null;
        }

    }

    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    String str = (String) msg.obj;
                    Toast.makeText(context, str, Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    Toast.makeText(context, getString(R.string.net_error), Toast.LENGTH_LONG).show();
                    break;
                case 2:

                    break;
                case 3:
                    String strstr = (String) msg.obj;
                    Log.e("----------","============");

                    break;
                case 4:

                    break;
            }
        }
    };

}
